<?php
namespace Wap\Controller;
use Think\Controller;
use Think\Log;
class WXPCASHOUT{
//	const SECRET = "bcf18ce53f49407b9040a577b8c388fa";
	const SECRET = "3eced11b140c44a4be53561adf92acf8";
//	const MC = "676988704626704384";//商户号
	const MC = "676988092351791104";//商户号
}

class XINCASHOUT{
    const SECRET = "2897d756dcc7c7abfd6822ef1774762e";
    const MC = "1724283130";//商户号
}
class WxcashoutController extends Controller {
    private $xmlArr;
	/*执行提现的操作*/
    	public function docashout($id,$bankcode){

    	    $mes = M('juejin_tiorder')->where( ['id'=>$id] )->find();

//            $tjurl = "http://paytest.shopping98.com/payment-liquidate/v1/gateway.shtml";
            $tjurl = "http://scpay.shopping98.com/v1/gateway.shtml"; /*被攻击时注释掉*/

            $para = array();
            $para['service'] = "v1_liquidation_pay";
            $para['version'] = "1.0";
            $para['merchant_no'] = WXPCASHOUT::MC;
            $para['charset'] = "UTF-8";
            $para['req_time'] = date("YmdHis", time() );
            $para['sign'] = "";
            $para['sign_type'] = "MD5";
            $para['nonce_str'] = createNoncestr();
//            $para['out_trade_no'] = 'C'.substr(time(),4,10).rand(10,99);
            $para['out_trade_no'] = $mes['ordersn'];
            $para['amount'] = $mes['price']*100;
            $para['account_no'] = $mes['cardnum'];//银行卡号
            $para['account_name'] = $mes['weixin'];
            $para['account_type'] = "00";
            $para['client_ip'] = get_client_ip();
            $para['order_time'] = date("YmdHis", time() );
            $para['id_type'] = "0";
            $para['id'] = $mes['card'];
            $para['bank_code'] = $bankcode;
            $para['currency'] = "CNY";
            $para['notify_url'] = C('WAP_DOMAIN').'/wap/wxcashout/notifyurl98';
    //
            ksort( $para );
            $signstr = "";
            $i = 0;
            foreach( $para as $key=>$item )
            {
                if( $key == "sign_type" || $key == "sign")
                {
                    continue;
                }
                if( $item == "" || $item == null )
                {
                    continue;
                }
                if( $i == 0 )
                {
                    $signstr = $key."=".$item;
                }else{
                    $signstr = $signstr."&".$key."=".$item;
                }
                $i++;
            }
            $signstr = $signstr.WXPCASHOUT::SECRET;
            $para['sign'] = strtolower(md5( $signstr ));

             $ch = curl_init();
             //设置超时
             curl_setopt($ch, CURLOPT_TIMEOUT, 30);
             curl_setopt($ch,CURLOPT_URL, $tjurl);
             curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
             curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
             //设置header
             curl_setopt($ch, CURLOPT_HEADER, FALSE);
             //要求结果为字符串且输出到屏幕上
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
             //post提交方式
             curl_setopt($ch, CURLOPT_POST, TRUE);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $para);
             //运行curl
             $data = curl_exec($ch);
             curl_close($ch);


             $str = var_export( $data,TRUE);
             file_put_contents("tixianshibai.txt",$str,FILE_APPEND);
             file_put_contents("tixianshibai.txt","\r\n",FILE_APPEND);

            //把同步返回结果保存到表中
            $sync = array();
            $sync['out_trade_no'] = $mes['ordersn'];

             //返回结果
             if($data)
             {
                $a1 = json_decode( $data, true );


                 $sync['resp_code'] = $a1['resp_code'];
                 $sync['resp_msg'] = $a1['resp_msg'];
                 if( $a1['resp_code'] == "0000" )
                 {
//
                     $sync['account_no'] = $a1['account_no'];
                     $sync['account_name'] = $a1['account_name'];
                     $sync['amount'] = $a1['amount'];
                     M("juejin_tisync")->add( $sync );
                     return "success";
                 }else{
                     M("juejin_tisync")->add( $sync );
                     return $a1['resp_msg'];
                }
             }else{
                 M("juejin_tisync")->add( $sync );
                 return "通信失败";
             }
    	}


    	/*用98的接口判断银行卡号是否有效*/
    	public function getbankIfVeri($cardno){
            $tjurl = "http://scpay.shopping98.com/v1/gateway.shtml";


            $para['service'] = "v1_liquidation_bankcard_query";
            $para['version'] = "1.0";
            $para['merchant_no'] = "676988092351791104";
            $para['charset'] = "UTF-8";
            $para['req_time'] = date("ymdHis", time() );
            $para['sign'] = "";
            $para['sign_type'] = "MD5";
            $para['nonce_str'] = createNoncestr();
            $para['card_no'] = $cardno;
            ksort( $para );
            $signstr = "";
            $i = 0;
            foreach( $para as $key=>$item )
            {
                if( $key == "sign_type" || $key == "sign")
                {
                    continue;
                }
                if( $item == "" || $item == null )
                {
                    continue;
                }
                if( $i == 0 )
                {
                    $signstr = $key."=".$item;
                }else{
                    $signstr = $signstr."&".$key."=".$item;
                }
                $i++;
            }
            $signstr = $signstr.WXPCASHOUT::SECRET;
            $para['sign'] = strtolower(md5( $signstr ));



            $ch = curl_init();
             //设置超时
             curl_setopt($ch, CURLOPT_TIMEOUT, 30);
             //这里设置代理，如果有的话
             //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
             //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
             curl_setopt($ch,CURLOPT_URL, $tjurl);
             curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
             curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
             //设置header
             curl_setopt($ch, CURLOPT_HEADER, FALSE);
             //要求结果为字符串且输出到屏幕上
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
             //post提交方式
             curl_setopt($ch, CURLOPT_POST, TRUE);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $para);
             //运行curl
             $data = curl_exec($ch);
             curl_close($ch);
             //返回结果


             $str = var_export( $data,TRUE);
             file_put_contents("kahaobuzhengque.txt",$str,FILE_APPEND);
             file_put_contents("kahaobuzhengque.txt","\r\n",FILE_APPEND);


             if($data)
             {
                $a1 = json_decode( $data, true );
                if( $a1['resp_code'] == "0000" )
                {
                    if( $a1['resp_msg'] == "成功" )
                    {
                        return $a1;
                    }
                }else{
                    return null;
                }
             }else{
                return null;
             }
    	}

        public function notifyurl98(){
            $xml = file_get_contents("php://input");
            file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
            file_put_contents("notifyurl98.txt",$xml,FILE_APPEND);


            $data['trans_no'] = $_POST['trans_no'];
            $data['charset'] = $_POST['charset'];
            $data['bank_code'] = $_POST['bank_code'];
            $data['amount'] = $_POST['amount'];
            $data['sign'] = $_POST['sign'];
            $data['version'] = $_POST['version'];
            $data['account_no'] = $_POST['account_no'];
            $data['resp_time'] = $_POST['resp_time'];
            $data['out_trade_no'] = $_POST['out_trade_no'];
            $data['account_name'] = $_POST['account_name'];
            $data['resp_code'] = $_POST['resp_code'];
            $data['sign_type'] = $_POST['sign_type'];
            $data['trans_status'] = $_POST['trans_status'];


            /*验证签名*/

            ksort( $data );

            $str = var_export( $data, true );
            file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
            file_put_contents("notifyurl98.txt",$str,FILE_APPEND);


            $signstr = "";
            $i = 0;
            foreach( $data as $key=>$item )
            {
                if( $key == "sign_type" || $key == "sign" )
                {
                    continue;
                }
                if( $item == "" || $item == null )
                {
                    continue;
                }
                if( $i == 0 )
                {
                    $signstr = $key."=".$item;
                }else{
                    $signstr = $signstr."&".$key."=".$item;
                }
                $i++;
            }

            $signstr = $signstr.WXPCASHOUT::SECRET;

            file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
            file_put_contents("notifyurl98.txt","签名",FILE_APPEND);
            file_put_contents("notifyurl98.txt",$signstr,FILE_APPEND);
            file_put_contents("notifyurl98.txt",",",FILE_APPEND);
            file_put_contents("notifyurl98.txt",$data['sign'],FILE_APPEND);
            file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);


            $sign = md5( $signstr );
            if( $sign == $data['sign'] )
            {
                if( $data['resp_code'] == "0000" && $data['trans_status']== "S" ){

                    file_put_contents("notifyurl98.txt","用户表里的余额复位",FILE_APPEND);
                    file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
                    $this->reducemoney($data['out_trade_no'], $_POST['amount']);
                }else{
                    /*提现失败，把buffer_money减去，money值复原*/
                    $this->cashfail($data['out_trade_no'], $_POST['amount']);
                }
            }else{
                file_put_contents("98提现失败.txt",$data['out_trade_no'],FILE_APPEND);
                file_put_contents("98提现失败.txt","\r\n",FILE_APPEND);
            }
        }



         /*Xin付的代付接口*/
        public function docashxin($id,$bank ){
            $bankname = substr($bank['bank_name'],0,strpos($bank['bank_name'],"("));
            $mes = M('juejin_tiorder')->where( ['id'=>$id] )->find();
//            $tjurl = "http://dfapi.xiipay.com/Transfer";/*被攻击时注释掉*/
//            sn 序列号 24位以内 商户唯一
//            		bankName 银行名称
//            		bankAccount 收款账号
//            		bankUserName 收款人
//            		amount 金额(单位分)
//            		account 代付账号
//            		remark 备注（原样返回）
//            		notifyurl 异步通知地址

            $para = array();
            $para['sn'] = $mes['ordersn'];
            $para['bankName'] = $bankname;
            $para['bankAccount'] = $mes['cardnum'];//银行卡号
            $para['bankUserName'] = $mes['weixin'];
            $para['amount'] = $mes['price']*100;
            $para['account'] = XINCASHOUT::MC;/*代付账号*/
            $para['remark'] = "xin提现";
            $para['notifyurl'] = C('WAP_DOMAIN').'/wap/wxcashout/notifyurlxin';

            // sn+account+bankAccount+amount+key
            $signstr = $para['sn'].$para['account'].$para['bankAccount'].$para['amount'].XINCASHOUT::SECRET;

            $para['sign'] = md5( $signstr );

            $parastr = "";
            $i = 0;
            foreach( $para as $key=>$item )
            {
                if( $i == 0 ){
                    $parastr = "?".$key."=".$item;
                }else{
                    $parastr = $parastr."&".$key."=".$item;
                }
                $i++;
            }
            $tjurl = $tjurl.$parastr;
            @header("Location:$tjurl");

        }

        public function notifyurlxin(){
            $xml = file_get_contents("php://input");
            file_put_contents("notifyurlxin.txt","\r\n",FILE_APPEND);
            file_put_contents("notifyurlxin.txt",$xml,FILE_APPEND);
            file_put_contents("notifyurlxin.txt","\r\n",FILE_APPEND);
            file_put_contents("notifyurlxin.txt",$_SERVER["QUERY_STRING"],FILE_APPEND);
        }

    /*提现失败*/
    public function cashfail($ordersn){
        $order = M('juejin_tiorder')->where(array('ordersn'=>$ordersn ))->select();
        if( $order ){
            M('juejin_users')->where(['id'=>$order[0]['userid']])->setDec('buffer_money',$order[0]['price'] );
            file_put_contents("notifyurl98.txt",M('juejin_users')->getLastSql(),FILE_APPEND);
            file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
            M('juejin_users')->where(['id'=>$order[0]['userid']])->setInc('money',$order[0]['price'] );
        }
    }

	public function reducemoney( $ordersn, $amount ){
         $order = M('juejin_tiorder')->where(array('ordersn'=>$ordersn ))->select();
         file_put_contents("notifyurl98.txt",M('juejin_users')->getLastSql(),FILE_APPEND);
         file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
         if( count( $order ) == 1 )
         {
            if( $order[0]['status'] != 2 )
            {
                // 提现确认时，更新user表
                M('juejin_users')->where(['id'=>$order[0]['userid']])->setDec('buffer_money',$amount/100 );
                file_put_contents("notifyurl98.txt",M('juejin_users')->getLastSql(),FILE_APPEND);
                file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
                M('juejin_tiorder')->where(array('ordersn'=>$ordersn))->save(['status'=>2,'paytime'=>time()]);
                file_put_contents("notifyurl98.txt",M('juejin_users')->getLastSql(),FILE_APPEND);
                file_put_contents("notifyurl98.txt","\r\n",FILE_APPEND);
            }
         }


//         $order = M('juejin_payorder')->where(array('ordersn'=>$ordersn ))->select();
//                 if( count( $order ) == 1 )
//                 {
//                     if($order[0]['status'] != 2){
//                         /*
//                         $price = 0.97 * floatval( $price );
//                         		$price = sprintf("%.2f", $price);
//                         */
//                         $monval = 0.97 * floatval( $order[0]['price'] );
//                         $monval = sprintf("%.2f", $monval);
//                         $monval2 = 0.03 * floatval( $order[0]['price'] );
//                         $monval2 = sprintf("%.2f", $monval2);
//
//
//                         M('juejin_payorder')->where(array('ordersn'=>$ordersn))->save(['status'=>2,'paytime'=>time()]);
//
//                         M('juejin_users')->where(['id'=>$order[0]['userid']])->setInc('money',$monval );
//
//                         M('juejin_users')->where(['id'=>$order[0]['userid']])->setInc('addmoney',$monval );
//
//                         /*积分日志*/
//                         $log['userid'] = $order[0]['userid'];
//                         $log['num'] = $monval;
//                         $log['type'] = 1;
//                         $log['createtime'] = time();
//                         $log['note'] = 1;
//                         M("juejin_integral_log")->add( $log );
//
//
//                         $log['userid'] = 0;
//                         $log['num'] = $monval2;
//                         $log['type'] = 1;
//                         $log['createtime'] = time();
//                         $log['note'] = 2;
//                         M("juejin_integral_log")->add( $log );
//
//                         return "success";;
//                     }else{
//                         return "success";
//                     }
//                 }else{
//                     return "trnorepeat";
//                 }

	}




}
?>
